package cc.vv.btpartyjob.partymanager.activity

import android.content.Intent
import android.text.TextUtils
import android.webkit.JavascriptInterface
import cc.vv.baselibrary.util.LKAppUtil
import cc.vv.baselibrary.util.LKJsonUtil
import cc.vv.baselibrary.util.UserInfoManageUtil
import cc.vv.baselibrary.view.BaseTopBarView
import cc.vv.baselibrary.view.BtWebView
import cc.vv.btpartyjob.jnimodule.activity.OrganizationActivity
import cc.vv.btpartyjob.jnimodule.api.JniH5API
import cc.vv.btpartyjob.jnimodule.globle.IntentJniKey
import cc.vv.btpartyjob.jnimodule.server.JniStartActivity
import cc.vv.btpartyjob.partymanager.delegate.LouDongTeamActivityDelegate
import cc.vv.btpartyjob.partymanager.delegate.ManagerBaseBinder
import cc.vv.mvp.activity.BaseActivityMVP
import cc.vv.mvp.binder.BaseDataBinder
import com.tencent.smtt.export.external.interfaces.SslError
import com.tencent.smtt.export.external.interfaces.SslErrorHandler
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import org.json.JSONObject

/**
 * 楼栋党小组
 * Created by Chen.qi on 2018/10/25.
 */
class LouDongTeamActivity : BaseActivityMVP<LouDongTeamActivityDelegate>() {

    private var webView: BtWebView? = null

    private var mJsInterface: JSInterface? = null

    private var isChoose = false


    override fun initData() {
        viewDelegate?.setTopBarTitle("楼栋党小组")
        viewDelegate?.initWebClient(MyWebViewClient(), MyWebCromeClient())
        webView = viewDelegate.getWebView()
        mJsInterface = JSInterface()
        webView?.addJavascriptInterface(mJsInterface, "BenchJSInterface")

        val intent = Intent(this@LouDongTeamActivity, OrganizationActivity::class.java)
        intent.putExtra(IntentJniKey.INTENT_KEY_ORG_TYPE, 6)
        intent.putExtra(IntentJniKey.INTENT_KEY_ORG_CHOOSE, 6)
        startActivityForResult(intent, 100)
    }

    override fun bindEvenListener() {
        viewDelegate?.setTitleBackBtnOnClick(object : BaseTopBarView.EventInterface {
            //返回
            override fun leftOnClick() {
                finish()
            }

            override fun leftCloseClick() {}
            override fun rightOnClick() {
                val intent = Intent(this@LouDongTeamActivity, OrganizationActivity::class.java)
                intent.putExtra(IntentJniKey.INTENT_KEY_ORG_TYPE, 6)
                intent.putExtra(IntentJniKey.INTENT_KEY_ORG_CHOOSE, 6)
                startActivityForResult(intent, 100)
            }
        })
    }

    override fun getDelegateClass(): Class<LouDongTeamActivityDelegate> {
        return LouDongTeamActivityDelegate::class.java
    }

    override fun getDataBinder(): BaseDataBinder<*, *> {
        return ManagerBaseBinder()
    }


    /**
     * MyWebViewClient
     */
    private inner class MyWebViewClient : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            view?.loadUrl(url)
            return true
        }

        override fun onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {}

        override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler, error: SslError?) {
            //接受所有证书
            handler.proceed()
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
        }
    }


    private inner class MyWebCromeClient : WebChromeClient() {

        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
//            val proView = getView<WebProgressView>(R.id.pv_awJni_progressBar)
            if (newProgress == 100) {
                //加载完毕进度条消失
//                proView?.visibility = View.GONE
                loading.closeLoading()
            } else {
                //更新进度
//                proView?.setProgress(newProgress)
                if (!loading.isShowing) {
                    loading.showLoading()
                }
            }
        }
    }


    /**
     * title内容
     */
    private var titleContent: String? = null

    /**
     * 点击类型
     * 0:隐藏右边半年
     * 1：时间选择
     * 2：组织选择
     */
    private var clickType: String? = null

    /**
     * 时间选择的js回调
     */
    private var timeJs: String? = null

    /**
     * 组织结构js回调
     */
    private var orgJs: String? = null

    /**
     * orgType 组织结构显示类型
     */
    private var orgType: Int = 0

    /**
     * orgChooseType 组织结构选择类型
     */
    private var orgChooseType: Int = 0


    /**
     * Js调用Android代码，点击H5网页的首页的"关闭"按钮调用Android代码关闭展示webView的Activity
     */
    private inner class JSInterface {
        /**
         * 设置标题Js回调
         */
        @JavascriptInterface
        fun setTitle(title: String) {
            titleContent = title
            handler.sendEmptyMessage(9)
        }

        /**
         * 设置右边图标
         * 0::隐藏
         * 1::显示固定图标
         */
        @JavascriptInterface
        fun setRightImage(typeJson: String?, js: String?) {
            timeJs = js
            orgJs = js
            val click: String?
            try {
                val json = JSONObject(typeJson)
                click = json.getString("clickType")
                clickType = click
                val type = json.getString("type")
                val chooseType = json.getString("chooseType")
                if (LKAppUtil.getInstance().isNumeric(type)) {
                    orgType = type.toInt()
                }
                if (LKAppUtil.getInstance().isNumeric(chooseType)) {
                    orgChooseType = chooseType.toInt()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            handler.sendEmptyMessage(10)
        }


        /**
         * 获取用户信息
         */
        @JavascriptInterface
        fun getUserToken(js: String) {
            val userInfo = UserInfoManageUtil.getUserInfo()
            val newJs = js.replace("->path<-", LKJsonUtil.objConversionJsonString(userInfo))
            webView?.loadUrl(newJs)
        }

        /**
         * 选择组织机构
         */
        @JavascriptInterface
        fun chooseOrg(json_: String, js: String) {
            val json = JSONObject(json_)
            val type: String?
            orgJs = js
            try {
                type = json.getString("type")
                val chooseType = json.getString("chooseType")
                var orgType = 0
                var orgChooseType = 0
                if (LKAppUtil.getInstance().isNumeric(type)) {
                    orgType = type.toInt()
                }
                if (LKAppUtil.getInstance().isNumeric(chooseType)) {
                    orgChooseType = chooseType.toInt()
                }
                JniStartActivity.startIntentOrganActivity(this@LouDongTeamActivity, orgType, orgChooseType,
                        100)

            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (null == data) {
            if (!isChoose) {
                finish()
            }
            return
        }
        if (requestCode == 100 && resultCode == 101) {
            val communityId = data.getStringExtra(IntentJniKey.INTENT_KEY_ORGAN_ID)
            if (communityId == oldChooseId) {
                return
            }
            oldChooseId = communityId
            val orgName = data.getStringExtra(IntentJniKey.INTENT_KEY_ORGAN_NAME)
            isChoose = true
            viewDelegate?.setTopBarTitle(orgName)
            if (!TextUtils.isEmpty(communityId)) {
                val url = JniH5API.louDongDangDetailUrl + communityId
                viewDelegate?.setWebViewUrl(url)
            }
        }
    }

    private var oldChooseId: String? = null


}